<?php

namespace App\Http\Controllers\Home;

use App\Models\Areas;
use App\Models\Cases;
use App\Models\Categorys;
use App\Models\Collections;
use App\Models\Footprints;
use App\Models\Services;
use App\Models\StoreEvaluates;
use App\Models\Stores;
use App\Models\UserInfos;
use App\Models\Users;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class StoreController extends Controller
{
    /**
     * 供应商列表页面
     * @param url home.store.storeList
     * @param Request $request
     * @param store_id 当前供应商id
     * @param store_name 当前供应商名称
     * @param content 评价内容
     * @param speed 工作速度评分
     * @param quality 工作质量评分
     * @param attitude 工作态度评分
     * @return bool
     */
    public function storeList(Request $request){

        return view('home.store.storeList');
    }

    /**
     * 供应商列表
     * @param url home.store.lists
     * @param Request $request
     * @param cid 一级分类id
     * @param cid_id 二级分类id
     * @param area 区域id
     * @param recommend 推荐 2:官网推荐 不传或其他：无要求
     * @param sid 排序id 1:致电量 2:成交量 3:浏览量 4:点赞量 不传或其他值：创建时间
     * @param orderby 'desc'倒叙 'asc'正序
     * @return bool
     */
    public function listsApi(Request $request)
    {
        try{
            $map = [
                'cid' => (int)$request->get('cid'),//一级分类id
                'cid_id' => (int)$request->get('cid_id'),//二级分类id
                'area' => (int)$request->get('area'),
                'recommend' => (int)$request->get('recommend'),
            ];
            $page = (int)$request->get('page',1);//页码
            $sid = (int)$request->get('sid');//排序
            $orderby = (string)$request->get('orderby','desc');//排序
            if ($sid == 1){
                $sort = 'service';
            }elseif ($sid == 2){
                $sort = 'view';
            }elseif ($sid == 3){
                $sort = 'praise';
            }else{
                $sort = 'created_at';
            }
            $lists = [];
            $lists['cate_id'] = Categorys::getcates(['pid'=>0],['id','name','pid']);//一级分类
            $fields = ['id','user_id','store_name','logo','phone','call','view','service','praise','service_scope','hot','quality'];
            //二级分类
            if(empty($map['cid'])){
                $lists['children'] = Categorys::where('pid','<>','0')->get(['id','name','pid'])->toArray();
            }else{
                $lists['children'] = Categorys::getcates(['pid'=>$map['cid']],['id','name','pid'])->toArray();
            }
            $lists['store'] = Stores::allLists($map, $fields, $page, 10, $sort, $orderby);
            foreach ($lists['store'] as $key=>$val){
                $lists['store'][$key]['view'] = strlen($val['view'])>=4 ? '999+' : $val['view'];
                $lists['store'][$key]['call'] = strlen($val['call'])>=4 ? '999+' : $val['call'];
                $lists['store'][$key]['praise'] = strlen($val['praise'])>=4 ? '999+' : $val['praise'];
                $lists['store'][$key]['service'] = strlen($val['service'])>=4 ? '999+' : $val['service'];
                $lists['store'][$key]['master_name'] = UserInfos::where('user_id',$val['user_id'])->value('master_name');
                $lists['store'][$key]['master_phone'] = UserInfos::where('user_id',$val['user_id'])->value('master_phone');
                $lists['store'][$key]['bool'] = false;
            }
            $lists['area'] = Areas::get(['id','name','pid']);//服务区域
            return $this->writeJson(0,$lists);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 右侧供应商
     * @param url home.store.rightStoreApi
     * @return bool
     */
    public function rightStoreApi()
    {
        try{
            $fields = ['id','user_id','store_name','logo','phone','call','view','service','praise','service_scope','hot','quality','credit'];
            $lists = Stores::allLists(['recommend'=>2],$fields, null, 3 );
            foreach ($lists as $key=>$val){
                $lists[$key]['view'] = strlen($val['view'])>=4 ? '999+' : $val['view'];
                $lists[$key]['call'] = strlen($val['call'])>=4 ? '999+' : $val['call'];
                $lists[$key]['praise'] = strlen($val['praise'])>=4 ? '999+' : $val['praise'];
                $lists[$key]['service'] = strlen($val['service'])>=4 ? '999+' : $val['service'];
                $lists[$key]['master_name'] = UserInfos::where('user_id',$val['user_id'])->value('master_name');
                $lists[$key]['master_phone'] = UserInfos::where('user_id',$val['user_id'])->value('master_phone');
                $lists[$key]['bool'] = false;
            }
            return $this->writeJson(0,$lists);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 供应商首页
     * @param url home.store.store
     * @param Request $request
     * @return bool
     */
    public function store(){
        return view('home.store.store');
    }

    /**
     * 供应商基本详情
     * @param url home.store.storeDetails
     * @param Request $request
     * @param id 供应商id
     * @return bool
     * @return is_collect 1:未收藏 2:已收藏
     */
    public function storeDetailsApi(Request $request){
        try{
            $id = (int)$request->get('id');//供应商id
            if (empty($id)) return $this->writeJson(1,null,'参数错误');
            $fields = ['id','store_name','logo','seller_name','cate_id','call','credit','collections','hot','quality','workingtime','area_info','description'];
            $lists = Stores::details(['id'=>$id], $fields);
            $lists['master_name'] = UserInfos::where('user_id',$lists['user_id'])->value('master_name');
            $lists['master_phone'] = UserInfos::where('user_id',$lists['user_id'])->value('master_phone');
            $lists['call'] = strlen($lists['call'])>=4 ? '999+' : $lists['call'];
            //二级分类
            $lists['cate_id'] = explode(',',$lists['cate_id']);
            foreach ($lists['cate_id'] as $k => $v){
                $pidTree[] =Categorys::where('id',$v)->first('name');
            }
            $lists['cate_id'] = $pidTree;
            //判断是否收藏
            $lists['is_collect'] = 1;//默认未收藏
            $userinfo = auth()->guard('web')->user();//获取当前登录用户
            if (!empty($userinfo)){
                if ($userinfo['type'] == 1){
                    $collect = Collections::where(['collect_id'=>$id,'user_id'=>$userinfo['id'],'type'=>4])->value('collect_id');
                    $lists['is_collect'] = empty($collect) ? 1 : 2;
                }
                //添加足迹
                $foot_arr = [
                    'user_id' => $userinfo['id'],
                    'foot_id' => $id,
                    'type'    => 1,
                ];
                Footprints::create($foot_arr);
            }
            Stores::where('id',$id)->increment('view');//浏览量加1
            return $this->writeJson(0,$lists);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 供应商简介页面
     * @param url home.store.storeSummary
     * @param Request $request
     * @return bool
     */
    public function storeSummary(){
        return view('home.store.summary');
    }

    /**
     * 供应商图片页面
     * @param url home.store.storeImg
     * @param Request $request
     * @return bool
     */
    public function storeImg(){
        return view('home.store.image');
    }

    /**
     * 供应商图片
     * @param url home.store.image
     * @param Request $request
     * @param id 供应商id
     * @return bool
     */
    public function imageApi(Request $request){
        try{
            $id = (int)$request->get('id');//供应商id
            if (empty($id)) return $this->writeJson(1,null,'参数错误');
            $lists = Stores::details(['id'=>$id],'image');
            return $this->writeJson(0,$lists);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 供应商服务列表页面
     * @param url home.store.storeService
     * @param Request $request
     * @return bool
     */
    public function storeService(){
        return view('home.store.service');
    }

    /**
     * 供应商服务
     * @param url home.store.service
     * @param Request $request
     * @param id 供应商id
     * @return bool
     * @return summary 简介
     */
    public function serviceApi(Request $request){
        try{
            $id = (int)$request->get('id');//供应商id
            if (empty($id)) return $this->writeJson(1,null,'参数错误');
            $lists = Services::allLists(['store_id'=>$id],['id','store_id','thumb','title','summary'], null, 30);
            return $this->writeJson(0,$lists);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 供应商服务详情页面
     * @param url home.store.serviceDetails
     * @param Request $request
     * @return bool
     */
    public function serviceDetails(){
        return view('home.store.servicedetails');
    }

    /**
     * 供应商服务详情
     * @param url home.store.serviceDetailsApi
     * @param Request $request
     * @param id 服务内容id
     * @return bool
     * @return summary 简介
     */
    public function serviceDetailsApi(Request $request){
        try{
            $id = (int)$request->get('id');//服务内容id
            if (empty($id)) return $this->writeJson(1,route('home.store.servicedetails'),'参数错误');
            $lists = Services::details(['id'=>$id]);
            return $this->writeJson(0,$lists);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 供应商案例页面
     * @param url home.store.storeCases
     * @param Request $request
     * @return bool
     */
    public function storeCases(){
        return view('home.store.cases');
    }

    /**
     * 供应商案例
     * @param url home.store.cases
     * @param Request $request
     * @param id 供应商id
     * @param page 页码
     * @return bool
     * @return summary 简介
     */
    public function casesApi(Request $request){
        try{
            $id = (int)$request->get('id');//供应商id
            $page = (int)$request->get('page');//页码
            if (empty($id)) return $this->writeJson(1,null,'参数错误');
            if (empty($page)) return $this->writeJson(1,null,'页码不能为空');
            $lists = Cases::allLists(['store_id'=>$id], ['id','store_id','thumb','title','summary'], $page, 10);
            return $this->writeJson(0,$lists);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 供应商案例详情页面
     * @param url home.store.casesDetails
     * @param Request $request
     * @return bool
     */
    public function casesDetails(){
        return view('home.store.casesdetails');
    }

    /**
     * 供应商案例详情
     * @param url home.store.casesDetailsApi
     * @param Request $request
     * @param id 案例id
     * @return bool
     * @return summary 简介
     */
    public function casesDetailsApi(Request $request){
        try{
            $id = (int)$request->get('id');//案例id
            if (empty($id)) return $this->writeJson(1,route('home.store.casesdetails'),'参数错误');
            $lists = Cases::details(['id'=>$id]);
            return $this->writeJson(0,$lists);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 供应商合作商页面
     * @param url home.store.storePartners
     * @param Request $request
     * @return bool
     */
    public function storePartners(){
        return view('home.store.partners');
    }

    /**
     * 供应商合作商
     * @param url home.store.partners
     * @param Request $request
     * @param id 供应商id
     * @return bool
     */
    public function partnersApi(Request $request){
        try{
            $id = (int)$request->get('id');//供应商id
            if (empty($id)) return $this->writeJson(1,null,'参数错误');
            $lists = Stores::details(['id'=>$id],'partners');
            return $this->writeJson(0,$lists);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 供应商评价页面
     * @param url home.store.storeEvaluates
     * @param Request $request
     * @return bool
     */
    public function storeEvaluates(){
        return view('home.store.evaluates');
    }

    /**
     * 供应商评价
     * @param url home.store.evaluatesList
     * @param Request $request
     * @param id 供应商id
     * @param type 1:好评 2：中评 3：差评
     * @param page 页码
     * @return bool
     * @return average_star 当前评价的平均星星(星星是几，就是几分)
     * @return avg_good 好评率
     * @return avg_speed 平均工作速度
     * @return avg_quality 平均工作质量
     * @return avg_quality 平均工作态度
     * @return good 好评数
     * @return middle 中评数
     * @return bad 差评数
     */
    public function evaluatesList(Request $request){
        try{
            $id = (int)$request->get('id');//供应商id
            if (empty($id)) return $this->writeJson(1,null,'参数错误');
            $page = (int)$request->get('page');//页码
            if (empty($page)) return $this->writeJson(1,null,'页码不能为空');
            $map = [
                'store_id' => $id,
                'type' => (int)$request->get('type',1),
            ];
            $lists = StoreEvaluates::allLists($map,['*'],$page,3);
            foreach ($lists as $k=>$v){
                $lists[$k]['user_name'] = '**'.mb_substr($v['user_name'],-2,4,"utf-8");
            }
            $sum = StoreEvaluates::counts(['store_id'=>$id]);//总评论数
            $good = StoreEvaluates::counts(['store_id'=>$id,'type'=>1]);//好评数
            $speed = StoreEvaluates::sums(['store_id'=>$id], 'speed');
            $quality = StoreEvaluates::sums(['store_id'=>$id], 'quality');
            $attitude = StoreEvaluates::sums(['store_id'=>$id], 'attitude');
            $store['avg_good'] = empty($sum) ? 0 : intval(round (($good/$sum)*100));//好评率
            $store['avg_speed'] = empty($sum) ? 0 : intval(round ($speed/$sum));//平均工作速度
            $store['avg_quality'] = empty($sum) ? 0 : intval(round ($quality/$sum));//平均工作质量
            $store['avg_attitude'] = empty($sum) ? 0 : intval(round ($attitude/$sum));//平均工作态度
            $store['good'] = $good;//好评数
            $store['middle'] = StoreEvaluates::counts(['store_id'=>$id,'type'=>2]);//中评数
            $store['bad'] = StoreEvaluates::counts(['store_id'=>$id,'type'=>3]);//差评数
            $evaluate['list'] = $lists;
            $evaluate['store'] = $store;
            return $this->writeJson(0,$evaluate);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 供应商收藏
     * @param url home.store.storeCollectApi
     * @param Request $request
     * @param collect_id 收藏内容id
     * @return bool
     */
    public function storeCollectApi(Request $request){
        try{
            $user_id = auth()->guard('web')->id();
            if (empty($user_id)) return $this->writeJson(1,null,'请先登录');
            $collect_id = (int)$request->post('collect_id');
            if (empty($collect_id)) return $this->writeJson(1,null,'参数错误');
            $userinfo = Users::where(['id'=>$user_id, 'status'=>1])->value('type');
            if (empty($userinfo)) return $this->writeJson(1,null,'用户不存在');
            if ($userinfo != 1) return $this->writeJson(1,null,'供应商不能收藏');
            $collect = Collections::where(['collect_id'=>$collect_id, 'user_id'=>$user_id, 'type'=>4])->value('id');
            if (empty($collect)){
                $params = [
                    'collect_id' => $collect_id,
                    'user_id' => $user_id,
                    'collect_at' => date('Y-m-d H:i:s'),
                    'type' => 4,
                ];
                Collections::create($params);
                Stores::where('id',$collect_id)->increment('collections');
                return $this->writeJson(0, null, '收藏成功');
            }else {
                Collections::where(['collect_id'=>$collect_id, 'user_id'=>$user_id, 'type'=>4])->delete();
                return $this->writeJson(0, null, '取消收藏成功');
            }
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 评价供应商
     * @param url home.store.storeEvaluatesApi
     * @param store_id 店铺id
     * @param content 评价内容
     * @param speed 速度
     * @param quality 质量
     * @param attitude 态度
     * @return bool
     */
    public function storeEvaluatesApi(Request $request){
        try{
            $user_id = auth()->guard('web')->id();
            if (empty($user_id)) return $this->writeJson(1,null,'请登录');
            $userinfo = Users::where(['id'=>$user_id, 'status'=>1])->first(['username','avatar','type']);
            if (empty($userinfo)) return $this->writeJson(1,null,'用户不存在');
            if($userinfo['type'] != 1)  return $this->writeJson(1,null,'HR才能评价供应商');
            //TODO 拨打了供应商的电话才可以评价。。。流程等电话信息下来后才写
            $params = [
                'user_id' => $user_id,
                'user_name' => $userinfo['username'],
                'user_avatar' => $userinfo['avatar'],
                'store_id' => (int)$request->post('store_id'),
                'content' => (string)$request->post('content'),
                'speed' => (int)$request->post('speed'),
                'quality' => (int)$request->post('quality'),
                'attitude' => (int)$request->post('attitude'),
            ];
            $params['store_name'] = Stores::where('id',$params['store_id'])->value('store_name');
            $params['average_star'] = intval(round(($params['speed']+$params['quality']+$params['attitude'])/3));//平均分
            if($params['average_star'] ==5 || $params['average_star'] == 4){
                $params['type'] = 1;//好评
            }elseif ($params['average_star'] ==3){
                $params['type'] = 2;//中评
            }elseif ($params['average_star'] ==2 || $params['average_star'] == 1){
                $params['type'] = 3;//差评
            }
            StoreEvaluates::create($params);
            Stores::where('id',$params['store_id'])->increment('praise');//评论量加1
            //计算好评率
            $all = StoreEvaluates::where(['store_id'=>$params['store_id']])->where('status','<>',-1)->count();
            $goods = StoreEvaluates::where(['store_id'=>$params['store_id'], 'type'=>1])->where('status','<>',-1)->count();
            $credit = $goods/$all*100;
            Stores::where('id',$params['store_id'])->update(['credit'=>$credit]);
            return $this->writeJson(0, null, '评价成功');
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }



}